<template>
  <div class="stock-inquiry">

    <!-- 搜索和过滤区域 -->
    <div class="search-filter-section">
      <el-form :model="searchForm" inline>
        <el-form-item label="货品">
          <el-input 
            v-model="searchForm.Product_Name" 
            placeholder="请输入货品名称/编号"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.Category_Name" placeholder="请选择" clearable style="width: 150px">
            <el-option label="电子产品" value="电子产品" />
            <el-option label="类别一1" value="类别一1" />
            <el-option label="告知好拼" value="告知好拼" />
            <el-option label="低值易耗品" value="低值易耗品" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="searchForm.Unit_Name" placeholder="请选择" clearable style="width: 150px">
       
          <el-option label="个" value="个" />
            <el-option label="米" value="米" />
            <el-option label="立方米" value="立方米" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-select v-model="searchForm.Warehouse_Name" placeholder="请选择" clearable style="width: 150px">
             <el-option label="仓库1" value="仓库1" />
            <el-option label="1号仓库" value="1号仓库" />
            <el-option label="2号仓库" value="2号仓库" />
            <el-option label="3号仓库" value="2号仓库" />
            <el-option label="4号仓库" value="2号仓库" />
            <el-option label="5号仓库" value="2号仓库" />
            <el-option label="666号仓库" value="主仓库" />
          </el-select>
        </el-form-item>
        <el-form-item label="货品条码">
          <el-input 
            v-model="searchForm.Internal_Code" 
            placeholder="请输入货品条码"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchForm.Status">显示停用商品</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="searchData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>


    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button type="primary" @click="handleExport">导出</el-button>
      <el-button @click="refreshData">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-table 
        :data="tableData" 
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="product_Number" label="货品编号" width="120" />
        <el-table-column prop="product_Name" label="货品名称" width="150" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="category_Name" label="货品类型" width="120" />
        <el-table-column prop="specifications" label="规格型号" width="100" />
        <el-table-column prop="unit_Name" label="单位" width="80" />
        <el-table-column prop="internal_Code" label="条码" width="120" />
        <el-table-column prop="warehouse_Name" label="仓库名称" width="120" />
        <el-table-column prop="storage_Name" label="库位名称" width="120" />
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
        <el-table-column prop="waitInTo" label="待入库" width="120" />
        <el-table-column prop="waitOutTo" label="待出库" width="120" />
        <el-table-column prop="warehouse_InOrOutCount" label="可用库存" width="120" />
        <el-table-column prop="availableAmount" label="可用库存金额" width="120" />
        <el-table-column prop="intTo" label="期初" width="120" />
        <el-table-column prop="end" label="期末" width="120" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-link type="primary" @click="viewFlow(scope.row)">出入库流水</el-link>
            <el-link type="primary" @click="viewDistribution(scope.row)" style="margin-left: 10px">库存分布</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 库存分布全屏弹窗 -->
  <el-dialog
    v-model="distributionDialogVisible"
    title="库存分布详情"
    :fullscreen="true"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="distribution-dialog"
  >
    <div class="distribution-content">
             <!-- 产品信息头部 -->
       <div class="product-header" v-if="currentProduct">
         <div class="product-info">
           <h2>{{ currentProduct.product_Name || currentProduct.productName || '未知产品' }}</h2>
           <div class="product-details">
             <span class="detail-item">货品编号：{{ currentProduct.product_Number || currentProduct.productNumber || '-' }}</span>
             <span class="detail-item">货品类型：{{ currentProduct.category_Name || '-' }}</span>
             <span class="detail-item">规格型号：{{ currentProduct.specifications || '-' }}</span>
             <span class="detail-item">单位：{{ currentProduct.unit_Name || '-' }}</span>
           </div>
         </div>
       </div>

             <!-- 统计卡片 -->
       <div class="statistics-cards">
         <div class="stat-card blue">
           <div class="stat-number">{{ distributionStats.currentStock || 0 }}</div>
           <div class="stat-label">当前库存</div>
         </div>
         <div class="stat-card blue">
           <div class="stat-number">{{ distributionStats.availableStock || 0 }}</div>
           <div class="stat-label">可用库存</div>
         </div>
         <div class="stat-card orange">
           <div class="stat-number">{{ distributionStats.pendingOutbound || 0 }}</div>
           <div class="stat-label">待出库</div>
         </div>
         <div class="stat-card orange">
           <div class="stat-number">{{ distributionStats.pendingInbound || 0 }}</div>
           <div class="stat-label">待入库</div>
         </div>
       </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleExportDistribution">导出</el-button>
        <el-button @click="refreshDistributionData">刷新</el-button>
      </div>

                           <!-- 库存分布表格 -->
        <div class="table-section">
          <el-table 
            :data="distributionData" 
            style="width: 100%"
            v-loading="distributionLoading"
          >
            <el-table-column type="index" label="序号" width="80" />
            <el-table-column prop="warehouse_Name" label="仓库名称" width="150">
            </el-table-column>
            <el-table-column prop="storage_Name" label="仓位名称" width="150">
            </el-table-column>
            <el-table-column prop="currentInventory" label="当前库存" width="120">
            </el-table-column>
            <el-table-column prop="warehouse_InOrOutCount" label="可用库存" width="120">
            </el-table-column>
            <el-table-column prop="waitInTo" label="待入库" width="120">
            </el-table-column>
            <el-table-column prop="waitOutTo" label="待出库" width="120">
            </el-table-column>
          </el-table>
        </div>

       <!-- 右下角关闭按钮 -->
       <div class="close-button-container">
         <el-button 
           type="primary" 
           size="large"
           circle
           @click="distributionDialogVisible = false"
           class="close-button"
         >
           <el-icon><Close /></el-icon>
         </el-button>
       </div>
     </div>
   </el-dialog>

  <!-- 出入库流水全屏弹窗 -->
  <el-dialog
    v-model="flowDialogVisible"
    title="出入库流水"
    :fullscreen="true"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="true"
    class="flow-dialog"
  >
    <div class="flow-content">
      <!-- 产品信息头部 -->
      <div class="product-header" v-if="currentProduct">
        <div class="product-info">
          <h2>{{ currentProduct.product_Name }} {{ currentProduct.product_Number || currentProduct.productNumber || '' }}</h2>
          <div class="product-details">
            <span class="detail-item">货品类型：{{ currentProduct.category_Name }}</span>
            <span class="detail-item">规格型号：{{ currentProduct.specifications }}</span>
            <span class="detail-item">单位：{{ currentProduct.unit_Name }}</span>
          </div>
        </div>
      </div>

      <!-- 搜索和过滤区域 -->
      <div class="search-filter-section">
        <el-form :model="flowSearchForm" inline>
                     <el-form-item label="出入库单号">
             <el-input 
               v-model="flowSearchForm.Warehouse_Code" 
               placeholder="请输入出库单号/入库单号"
               style="width: 200px"
             />
           </el-form-item>
           <el-form-item label="仓库名称">
             <el-select v-model="flowSearchForm.Warehouse_Name" placeholder="请选择" clearable style="width: 150px">
               <el-option 
                 v-for="warehouse in warehouseOptions" 
                 :key="warehouse.value" 
                 :label="warehouse.label" 
                 :value="warehouse.value" 
               />
             </el-select>
          </el-form-item>
                     <el-form-item label="业务类型">
             <el-select v-model="flowSearchForm.WarehouseType" placeholder="请选择" clearable style="width: 150px">
               <el-option label="入库" :value=1 />
               <el-option label="出库" :value=2 />
             </el-select>
           </el-form-item>
           <el-form-item label="出入库类型">
             <el-select v-model="flowSearchForm.Warehousing_Type" placeholder="请选择" clearable style="width: 150px">
              <el-option label="进货入库" value="进货入库" />
              <el-option label="销售出库" value="销售出库" />
              <el-option label="调拨入库" value="调拨入库" />
              <el-option label="调拨出库" value="调拨出库" />
            </el-select>
          </el-form-item>
                     <el-form-item label="出入库日期">
             <el-date-picker
               v-model="flowSearchForm.startDate"
               type="daterange"
               range-separator="至"
               start-placeholder="开始日期"
               end-placeholder="结束日期"
               style="width: 250px"
             />
           </el-form-item>
                       <el-form-item label="制单日期">
              <el-date-picker
                v-model="flowSearchForm.CreateTime"
                type="date"
                placeholder="请选择制单日期"
                style="width: 200px"
              />
            </el-form-item>
          <el-form-item>
            <el-button @click="resetFlowSearch">重置</el-button>
            <el-button type="primary" @click="searchFlowData">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

             <!-- 统计卡片 -->
       <div class="statistics-cards">
         <div class="stat-card blue">
           <div class="stat-number">{{ flowStats.inboundQuantity }}</div>
           <div class="stat-label">入库数量</div>
         </div>
         <div class="stat-card blue">
           <div class="stat-number">{{ flowStats.inboundAmount }}</div>
           <div class="stat-label">入库金额</div>
         </div>
         <div class="stat-card orange">
           <div class="stat-number">{{ flowStats.outboundQuantity }}</div>
           <div class="stat-label">出库数量</div>
         </div>
         <div class="stat-card orange">
           <div class="stat-number">{{ flowStats.outboundAmount }}</div>
           <div class="stat-label">出库金额</div>
         </div>
       </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="handleExportFlow">导出</el-button>
        <el-button @click="refreshFlowData">刷新</el-button>
      </div>

      <!-- 数据表格 -->
      <div class="table-section">
        <el-table 
          :data="flowData" 
          style="width: 100%"
          v-loading="flowLoading"
          @selection-change="handleFlowSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="80" />
          <el-table-column prop="warehouse_Code" label="出入库单号" width="150" />
                     <el-table-column prop="reviewTime" label="出入库日期" width="120">
             <template #default="scope">
               <span>{{ formatDateTime(scope.row.reviewTime) }}</span>
             </template>
           </el-table-column>
                     <el-table-column prop="warehouseType" label="业务类型" width="100">
             <template #default="scope">
               <span v-if="scope.row.warehouseType === 1">入库</span>
               <span v-else-if="scope.row.warehouseType === 2">出库</span>
               <span v-else>{{ scope.row.warehouseType }}</span>
             </template>
           </el-table-column>
          <el-table-column prop="warehousing_Type" label="出入库类型" width="120" />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="120" />
                     <el-table-column prop="warehouse_InOrOutCount" label="入库数量" width="100">
             <template #default="scope">
               <span v-if="scope.row.warehouseType === 1">{{ scope.row.warehouse_InOrOutCount || 0 }}</span>
               <span v-else>-</span>
             </template>
           </el-table-column>
           <el-table-column prop="warehouse_InOrOutCount" label="出库数量" width="100">
             <template #default="scope">
               <span v-if="scope.row.warehouseType === 2">{{ scope.row.warehouse_InOrOutCount || 0 }}</span>
               <span v-else>-</span>
             </template>
           </el-table-column>
                     <el-table-column prop="total_Price" label="入库金额" width="120">
             <template #default="scope">
               <span v-if="scope.row.warehouseType === 1">{{ scope.row.total_Price || 0 }}</span>
               <span v-else>-</span>
             </template>
           </el-table-column>
           <el-table-column prop="total_Price" label="出库金额" width="120">
             <template #default="scope">
               <span v-if="scope.row.warehouseType === 2">{{ scope.row.total_Price || 0 }}</span>
               <span v-else>-</span>
             </template>
           </el-table-column>
          <el-table-column prop="reviewer" label="经办人" width="100" />
          <el-table-column prop="createUse" label="制单人" width="100" />
                     <el-table-column prop="createTime" label="制单时间" width="120">
             <template #default="scope">
               <span>{{ formatDateTime(scope.row.createTime) }}</span>
             </template>
           </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="flowCurrentPage"
            v-model:page-size="flowPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="flowTotal"
            layout="total, sizes, prev, pager, next"
            @size-change="handleFlowSizeChange"
            @current-change="handleFlowCurrentChange"
          />
        </div>
      </div>

      <!-- 右下角关闭按钮 -->
      <div class="close-button-container">
        <el-button 
          type="primary" 
          size="large"
          circle
          @click="flowDialogVisible = false"
          class="close-button"
        >
          <el-icon><Close /></el-icon>
        </el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { BusinessRed } from '@/http/axiosHelper'
import { ElMessage } from 'element-plus'
import { Close } from '@element-plus/icons-vue'

// 响应式数据
const activeTimeFilter = ref('today')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const selectedRows = ref([])
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  Product_Name: '',
  Category_Name: '',
  Unit_Name: '',
  Warehouse_Name: '',
  Internal_Code: '',
  Status: '',
})

// 表格数据
const tableData = ref([])

// 选项数据
const categoryOptions = ref([])
const warehouseOptions = ref([])
const unitOptions = ref([])

// 获取选项数据
const fetchOptions = async () => {
  try {
    console.log('开始获取选项数据...')
    
    // 获取货品类型选项
    try {
      const categoryResponse = await BusinessRed.get('/api/Ledger/GetCategories')
      if (categoryResponse.data && categoryResponse.data.data) {
        categoryOptions.value = categoryResponse.data.data.map(item => ({
          label: item.category_Name || item.name,
          value: item.category_Name || item.name
        }))
        console.log('货品类型选项获取成功:', categoryOptions.value)
      }
    } catch (error) {
      console.error('获取货品类型选项失败:', error)
    }

    // 获取仓库选项
    try {
      const warehouseResponse = await BusinessRed.get('/api/Ledger/GetWarehouses')
      if (warehouseResponse.data && warehouseResponse.data.data) {
        warehouseOptions.value = warehouseResponse.data.data.map(item => ({
          label: item.warehouse_Name || item.name,
          value: item.warehouse_Name || item.name
        }))
        console.log('仓库选项获取成功:', warehouseOptions.value)
      }
    } catch (error) {
      console.error('获取仓库选项失败:', error)
    }

    // 获取单位选项
    try {
      const unitResponse = await BusinessRed.get('/api/Ledger/GetUnits')
      if (unitResponse.data && unitResponse.data.data) {
        unitOptions.value = unitResponse.data.data.map(item => ({
          label: item.unit_Name || item.name,
          value: item.unit_Name || item.name
        }))
        console.log('单位选项获取成功:', unitOptions.value)
      }
    } catch (error) {
      console.error('获取单位选项失败:', error)
    }

    // 如果获取失败，使用默认选项
    if (categoryOptions.value.length === 0) {
      categoryOptions.value = [
        { label: '电子产品', value: '电子产品' },
        { label: '低值易耗品', value: '低值易耗品' }
      ]
    }
    if (warehouseOptions.value.length === 0) {
      warehouseOptions.value = [
        { label: '主仓库', value: '主仓库' },
        { label: '1号仓库', value: '1号仓库' },
        { label: '2号仓库', value: '2号仓库' }
      ]
    }
    if (unitOptions.value.length === 0) {
      unitOptions.value = [
        { label: '个', value: '个' },
        { label: '米', value: '米' },
        { label: '立方米', value: '立方米' }
      ]
    }
    
    console.log('选项数据获取完成')
  } catch (error) {
    console.error('获取选项数据失败:', error)
    // 使用默认选项
    categoryOptions.value = [
      { label: '电子产品', value: '电子产品' },
      { label: '低值易耗品', value: '低值易耗品' }
    ]
    warehouseOptions.value = [
      { label: '主仓库', value: '主仓库' },
      { label: '1号仓库', value: '1号仓库' },
      { label: '2号仓库', value: '2号仓库' }
    ]
    unitOptions.value = [
      { label: '个', value: '个' },
      { label: '米', value: '米' },
      { label: '立方米', value: '立方米' }
    ]
  }
}

// 获取数据方法
const fetchData = async () => {
  loading.value = true
  
  try {
    const params = {
      Product_Name: searchForm.Product_Name || '',
      Category_Name: searchForm.Category_Name || '',
      Unit_Name: searchForm.Unit_Name || '',
      Warehouse_Name: searchForm.Warehouse_Name || '',
      Internal_Code: searchForm.Internal_Code || '',
      Status: searchForm.Status || '',
      PageIndex: currentPage.value,
      PageSize: pageSize.value
    }

    console.log('查询参数:', params)

    const response = await BusinessRed.get('/api/Ledger/GetLedgar', { params })
    
    console.log('查询结果:', response)
    
    if (response.data && response.data.data) {
      // 处理数据，确保字段名正确
      const processedData = response.data.data.map(item => ({
        product_Number: item.product_Number || item.productNumber || item.Product_Number || '',
        product_Name: item.product_Name || item.productName || item.Product_Name || '',
        status: item.status || item.Status || '正常',
        category_Name: item.category_Name || item.categoryName || item.Category_Name || '',
        specifications: item.specifications || item.Specifications || '',
        unit_Name: item.unit_Name || item.unitName || item.Unit_Name || '',
        internal_Code: item.internal_Code || item.internalCode || item.Internal_Code || '',
        warehouse_Name: item.warehouse_Name || item.warehouseName || item.Warehouse_Name || '',
        storage_Name: item.storage_Name || item.storageName || item.Storage_Name || '',
        currentInventory: Number(item.currentInventory || item.currentStock || item.CurrentInventory || 0),
        waitInTo: Number(item.waitInTo || item.pendingInbound || item.WaitInTo || 0),
        waitOutTo: Number(item.waitOutTo || item.pendingOutbound || item.WaitOutTo || 0),
        warehouse_InOrOutCount: Number(item.warehouse_InOrOutCount || item.availableStock || item.Warehouse_InOrOutCount || 0),
        availableAmount: Number(item.availableAmount || item.AvailableAmount || 0),
        intTo: Number(item.intTo || item.IntTo || 0),
        end: Number(item.end || item.End || 0),
        // 保留原始数据用于其他操作
        ...item
      }))
      
      tableData.value = processedData
      total.value = response.data.totalCount || 0
      console.log('设置表格数据:', tableData.value)
      console.log('设置总数:', total.value)
    } else {
      console.log('响应数据为空或格式不正确')
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('查询失败:', error)
    console.error('错误详情:', error.response?.data)
    console.error('错误状态:', error.response?.status)
    tableData.value = []
    total.value = 0
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间，去掉T
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  return dateTimeStr.replace('T', ' ')
}

// 方法
const handleTimeFilterChange = (tab) => {
  console.log('时间筛选变化:', tab.props.name)
  fetchData()
}

const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'Status' ? '' : ''
  })
  currentPage.value = 1
  fetchData()
}

const searchData = () => {
  console.log('搜索条件:', searchForm)
  currentPage.value = 1
  fetchData()
}

// 导出函数
async function handleExport() {
    try {
        // 显示加载提示
        ElMessage.info('正在导出数据，请稍候...')
        
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BusinessRed({
            url: '/api/Ledger/GetledgarExport', // 后端接口地址
            method: 'GET',
            params: {
                // 传递搜索条件
                Product_Name: searchForm.Product_Name || '',
                Category_Name: searchForm.Category_Name || '',
                Unit_Name: searchForm.Unit_Name || '',
                Warehouse_Name: searchForm.Warehouse_Name || '',
                Internal_Code: searchForm.Internal_Code || '',
                Status: searchForm.Status || '',
                // 分页参数（导出时通常不需要分页，但保留以防后端需要）
                PageIndex: currentPage.value,
                PageSize: pageSize.value,
            },
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        // 5. 显示成功提示
        ElMessage.success('导出成功！')

    } catch (error) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '库存查询.xlsx'; // 默认文件名

    // 尝试多种文件名提取方式
    let fileName = '库存查询.xlsx';
    
    // 方式1：标准格式 filename="xxx"
    const standardMatch = contentDisposition.match(/filename="([^"]+)"/);
    if (standardMatch) {
        fileName = standardMatch[1];
    }
    // 方式2：UTF-8编码格式 filename*=UTF-8''xxx
    else {
        const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/);
        if (utf8Match) {
            fileName = decodeURIComponent(utf8Match[1]);
        }
        // 方式3：简单格式 filename=xxx
        else {
            const simpleMatch = contentDisposition.match(/filename=([^;]+)/);
            if (simpleMatch) {
                fileName = decodeURIComponent(simpleMatch[1]);
            }
        }
    }
    
    // 确保文件名有正确的扩展名
    if (!fileName.toLowerCase().endsWith('.xlsx') && !fileName.toLowerCase().endsWith('.xls')) {
        fileName += '.xlsx';
    }
    
    return fileName;
}

const refreshData = () => {
  console.log('刷新数据')
  fetchData()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
  console.log('选中的行:', selection)
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  console.log('每页显示数量变化:', size)
  fetchData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  console.log('当前页变化:', page)
  fetchData()
}

const viewFlow = async (row) => {
  console.log('查看出入库流水:', row)
  currentProduct.value = row
  flowDialogVisible.value = true
  
  // 获取出入库流水数据
  await fetchFlowData()
}

// 库存分布弹窗相关数据
const distributionDialogVisible = ref(false)
const currentProduct = ref(null)
const distributionData = ref([])
const distributionLoading = ref(false)

// 库存分布统计数据
const distributionStats = ref({
  currentStock: 0,
  availableStock: 0,
  pendingOutbound: 0,
  pendingInbound: 0
})

const viewDistribution = async (row) => {
  console.log('查看库存分布:', row)
  console.log('产品详细信息:', {
    product_Id: row.product_Id,
    productId: row.productId,
    product_Name: row.product_Name,
    productName: row.productName,
    product_Number: row.product_Number,
    productNumber: row.productNumber
  })
  
  currentProduct.value = row
  distributionDialogVisible.value = true
  
  // 获取库存分布数据
  await fetchDistributionData(row)
}

// 获取库存分布数据
const fetchDistributionData = async (product) => {
  distributionLoading.value = true
  
  try {
    const params = {
      Product_Id: product.product_Id || product.productId || '',
      Product_Name: product.product_Name || product.productName || '',
      Product_Number: product.product_Number || product.productNumber || '',
      PageIndex: 1,
      PageSize: 100
    }

    console.log('库存分布查询参数:', params)

    const response = await BusinessRed.get('/api/Ledger/GetDistribution', { params })
    
    console.log('库存分布查询结果:', response)
    
    if (response.data && response.data.data) {
      // 处理数据，确保字段名正确
      const processedData = response.data.data.map(item => ({
        warehouse_Name: item.warehouse_Name || item.warehouseName || item.Warehouse_Name || '',
        storage_Name: item.storage_Name || item.storageName || item.Storage_Name || '',
        currentInventory: Number(item.currentInventory || item.currentStock || item.CurrentInventory || 0),
        warehouse_InOrOutCount: Number(item.warehouse_InOrOutCount || item.availableStock || item.Warehouse_InOrOutCount || 0),
        waitInTo: Number(item.waitInTo || item.pendingInbound || item.WaitInTo || 0),
        waitOutTo: Number(item.waitOutTo || item.pendingOutbound || item.WaitOutTo || 0)
      }))
      
      distributionData.value = processedData
      
      // 计算统计数据
      distributionStats.value = {
        currentStock: processedData.reduce((sum, item) => sum + item.currentInventory, 0),
        availableStock: processedData.reduce((sum, item) => sum + item.warehouse_InOrOutCount, 0),
        pendingOutbound: processedData.reduce((sum, item) => sum + item.waitOutTo, 0),
        pendingInbound: processedData.reduce((sum, item) => sum + item.waitInTo, 0)
      }
      
      console.log('设置库存分布数据:', distributionData.value)
      console.log('设置统计数据:', distributionStats.value)
    } else {
      console.log('库存分布响应数据为空或格式不正确')
      distributionData.value = []
      distributionStats.value = {
        currentStock: 0,
        availableStock: 0,
        pendingOutbound: 0,
        pendingInbound: 0
      }
    }
  } catch (error) {
    console.error('获取库存分布数据失败:', error)
    console.error('错误详情:', error.response?.data)
    console.error('错误状态:', error.response?.status)
    
    let errorMessage = '获取库存分布数据失败，请稍后重试'
    if (error.response?.status === 404) {
      errorMessage = '库存分布接口不存在，请联系管理员'
    } else if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
    } else if (error.response?.status === 500) {
      errorMessage = '服务器内部错误，请联系管理员'
    } else if (!error.response) {
      errorMessage = '网络连接失败，请检查网络连接'
    }
    
    distributionData.value = []
    distributionStats.value = {
      currentStock: 0,
      availableStock: 0,
      pendingOutbound: 0,
      pendingInbound: 0
    }
    ElMessage.error(errorMessage)
  } finally {
    distributionLoading.value = false
  }
}

// 刷新库存分布数据
const refreshDistributionData = async () => {
  if (currentProduct.value) {
    await fetchDistributionData(currentProduct.value)
  }
}

// 导出库存分布数据
const handleExportDistribution = async () => {
  try {
    ElMessage.info('正在导出库存分布数据，请稍候...')
    
    const response = await BusinessRed({
      url: '/api/Ledger/GetDistributionExport',
      method: 'GET',
      params: {
        Product_Id: currentProduct.value?.product_Id || currentProduct.value?.productId || '',
        Product_Name: currentProduct.value?.product_Name || currentProduct.value?.productName || '',
        Product_Number: currentProduct.value?.product_Number || currentProduct.value?.productNumber || '',
      },
      responseType: 'blob',
    });

    const fileName = getFileNameFromHeaders(response.headers);
    const blob = new Blob([response.data], {
      type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success('库存分布数据导出成功！')
  } catch (error) {
    console.error('导出库存分布数据失败：', error);
    ElMessage.error('导出失败，请稍后重试');
  }
}

// 出入库流水弹窗相关数据
const flowDialogVisible = ref(false)
const flowSearchForm = reactive({
  Warehouse_Code: '',
  Warehousing_Type: '',
  Warehouse_Name: '',
  WarehouseType: '',
  startDate: null,
  EndDate: null,
  CreateTime: null,
})
const flowData = ref([])
const flowLoading = ref(false)
const flowCurrentPage = ref(1)
const flowPageSize = ref(10)
const flowTotal = ref(0)
const flowSelectedRows = ref([])

// 出入库流水统计数据
const flowStats = ref({
  inboundQuantity: 0,
  inboundAmount: 0,
  outboundQuantity: 0,
  outboundAmount: 0,
})

const searchFlowData = () => {
  console.log('出入库流水搜索条件:', flowSearchForm)
  flowCurrentPage.value = 1
  fetchFlowData()
}

const resetFlowSearch = () => {
  Object.keys(flowSearchForm).forEach(key => {
    if (key === 'startDate' || key === 'EndDate' || key === 'CreateTime') {
      flowSearchForm[key] = null
    } else {
      flowSearchForm[key] = ''
    }
  })
  flowCurrentPage.value = 1
  console.log('重置后的出入库流水搜索表单:', flowSearchForm)
  fetchFlowData()
}

const fetchFlowData = async () => {
  flowLoading.value = true
  
  try {
    const params = {
      Product_Id: currentProduct.value?.product_Id || currentProduct.value?.productId || '',
      Product_Name: currentProduct.value?.product_Name || currentProduct.value?.productName || '',
      Product_Number: currentProduct.value?.product_Number || currentProduct.value?.productNumber || '',
      Warehouse_Code: flowSearchForm.Warehouse_Code || '',
      Warehouse_Name: flowSearchForm.Warehouse_Name || '',
      Warehousing_Type: flowSearchForm.Warehousing_Type || '',
      WarehouseType: flowSearchForm.WarehouseType || '',
      startDate: flowSearchForm.startDate && flowSearchForm.startDate[0] ? flowSearchForm.startDate[0].toISOString().split('T')[0] : '',
      EndDate: flowSearchForm.startDate && flowSearchForm.startDate[1] ? flowSearchForm.startDate[1].toISOString().split('T')[0] : '',
      CreateTime: flowSearchForm.CreateTime ? flowSearchForm.CreateTime.toISOString().split('T')[0] : '',
      PageIndex: flowCurrentPage.value,
      PageSize: flowPageSize.value,
    }

    console.log('出入库流水查询参数:', params)

    const response = await BusinessRed.get('/api/Ledger/GetWarehouse_InOrOut', { params })
    
    console.log('出入库流水查询结果:', response)
    
    if (response.data && response.data.data) {
      // 处理数据，确保字段名正确
      const processedData = response.data.data.map(item => ({
        warehouse_Code: item.warehouse_Code || item.warehouseCode || item.Warehouse_Code || '',
        reviewTime: item.reviewTime || item.ReviewTime || '',
        warehouseType: Number(item.warehouseType || item.WarehouseType || 0),
        warehousing_Type: item.warehousing_Type || item.warehousingType || item.Warehousing_Type || '',
        warehouse_Name: item.warehouse_Name || item.warehouseName || item.Warehouse_Name || '',
        warehouse_InOrOutCount: Number(item.warehouse_InOrOutCount || item.Warehouse_InOrOutCount || 0),
        total_Price: Number(item.total_Price || item.totalPrice || item.Total_Price || 0),
        reviewer: item.reviewer || item.Reviewer || '',
        createUse: item.createUse || item.createUser || item.CreateUse || '',
        createTime: item.createTime || item.createTime || item.CreateTime || '',
        // 保留原始数据
        ...item
      }))
      
      flowData.value = processedData
      flowTotal.value = response.data.totalCount || 0
      
      // 根据业务类型计算统计数据
      let inboundQuantity = 0
      let inboundAmount = 0
      let outboundQuantity = 0
      let outboundAmount = 0
      
      processedData.forEach(item => {
        if (item.warehouseType === 1) {
          inboundQuantity += Number(item.warehouse_InOrOutCount) || 0
          inboundAmount += Number(item.total_Price) || 0
        } else if (item.warehouseType === 2) {
          outboundQuantity += Number(item.warehouse_InOrOutCount) || 0
          outboundAmount += Number(item.total_Price) || 0
        }
      })
      
      flowStats.value = {
        inboundQuantity,
        inboundAmount,
        outboundQuantity,
        outboundAmount
      }
      
      console.log('设置出入库流水数据:', flowData.value)
      console.log('设置出入库流水总数:', flowTotal.value)
      console.log('设置统计数据:', flowStats.value)
    } else {
      console.log('出入库流水响应数据为空或格式不正确')
      flowData.value = []
      flowTotal.value = 0
      flowStats.value = {
        inboundQuantity: 0,
        inboundAmount: 0,
        outboundQuantity: 0,
        outboundAmount: 0
      }
    }
  } catch (error) {
    console.error('获取出入库流水数据失败:', error)
    console.error('错误详情:', error.response?.data)
    console.error('错误状态:', error.response?.status)
    console.error('错误信息:', error.message)
    
    let errorMessage = '获取出入库流水数据失败，请稍后重试'
    if (error.response?.status === 404) {
      errorMessage = '出入库流水接口不存在，请联系管理员'
    } else if (error.response?.status === 401) {
      errorMessage = '登录已过期，请重新登录'
    } else if (error.response?.status === 500) {
      errorMessage = '服务器内部错误，请联系管理员'
    } else if (!error.response) {
      errorMessage = '网络连接失败，请检查网络连接'
    }
    
    flowData.value = []
    flowTotal.value = 0
    flowStats.value = {
      inboundQuantity: 0,
      inboundAmount: 0,
      outboundQuantity: 0,
      outboundAmount: 0
    }
    ElMessage.error(errorMessage)
  } finally {
    flowLoading.value = false
  }
}

const handleFlowSelectionChange = (selection) => {
  flowSelectedRows.value = selection
  console.log('选中的出入库流水行:', selection)
}

const handleFlowSizeChange = (size) => {
  flowPageSize.value = size
  flowCurrentPage.value = 1
  console.log('出入库流水每页显示数量变化:', size)
  fetchFlowData()
}

const handleFlowCurrentChange = (page) => {
  flowCurrentPage.value = page
  console.log('出入库流水当前页变化:', page)
  fetchFlowData()
}

async function handleExportFlow() {
    try {
        // 显示加载提示
        ElMessage.info('正在导出出入库流水数据，请稍候...')
        
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BusinessRed({
            url: '/api/Ledger/GetWarehouse_InOrOutExport', // 后端接口地址
            method: 'GET',
            params: {
                // 传递产品信息
                Product_Id: currentProduct.value?.product_Id || currentProduct.value?.productId || '',
                Product_Name: currentProduct.value?.product_Name || currentProduct.value?.productName || '',
                Product_Number: currentProduct.value?.product_Number || currentProduct.value?.productNumber || '',
                // 传递查询条件
                Warehouse_Code: flowSearchForm.Warehouse_Code || '',
                Warehouse_Name: flowSearchForm.Warehouse_Name || '',
                Warehousing_Type: flowSearchForm.Warehousing_Type || '',
                WarehouseType: flowSearchForm.WarehouseType || '',
                startDate: flowSearchForm.startDate && flowSearchForm.startDate[0] ? flowSearchForm.startDate[0].toISOString().split('T')[0] : '',
                EndDate: flowSearchForm.startDate && flowSearchForm.startDate[1] ? flowSearchForm.startDate[1].toISOString().split('T')[0] : '',
                CreateTime: flowSearchForm.CreateTime ? flowSearchForm.CreateTime.toISOString().split('T')[0] : '',
                // 分页参数
                PageIndex: flowCurrentPage.value,
                PageSize: flowPageSize.value,
            },
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        });

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders(response.headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

        // 5. 显示成功提示
        ElMessage.success('出入库流水数据导出成功！')

    } catch (error) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请稍后重试');
    }
}



const refreshFlowData = () => {
  console.log('刷新出入库流水数据')
  fetchFlowData()
}

// 生命周期
onMounted(async () => {
  console.log('库存查询页面已加载')
  try {
    console.log('开始获取选项数据...')
    await fetchOptions() // 先获取选项数据
    console.log('选项数据获取完成，开始获取表格数据...')
    await fetchData() // 再获取表格数据
    console.log('页面初始化完成')
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面初始化失败，请刷新重试')
  }
})
</script>








<style scoped>
.stock-inquiry {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.time-filters {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-filter-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card.blue .stat-number {
  color: #409eff;
  font-size: 24px;
  font-weight: bold;
}

.stat-card.green .stat-number {
  color: #67c23a;
  font-size: 24px;
  font-weight: bold;
}

.stat-card.orange .stat-number {
  color: #e6a23c;
  font-size: 24px;
  font-weight: bold;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-top: 8px;
}

.action-buttons {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.pagination-section {
  padding: 20px;
  text-align: right;
  background: white;
  border-top: 1px solid #ebeef5;
}

:deep(.el-tabs__item.is-active) {
  color: #67c23a;
}

:deep(.el-tabs__active-bar) {
  background-color: #67c23a;
}

:deep(.el-table) {
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
}

:deep(.el-link) {
  font-size: 14px;
}

/* 库存分布弹窗样式 */
.distribution-dialog {
  :deep(.el-dialog) {
    margin: 0;
    border-radius: 0;
  }
  
  :deep(.el-dialog__header) {
    background: #f5f5f5;
    padding: 15px 20px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 60px);
    overflow-y: auto;
  }
}

.distribution-content {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.product-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.product-info h2 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 24px;
}

.product-details {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.detail-item {
  color: #606266;
  font-size: 14px;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card.blue .stat-number {
  color: #409eff;
  font-size: 28px;
  font-weight: bold;
}

.stat-card.orange .stat-number {
  color: #e6a23c;
  font-size: 28px;
  font-weight: bold;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-top: 8px;
}

.action-buttons {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

/* 出入库流水弹窗样式 */
.flow-dialog {
  :deep(.el-dialog) {
    margin: 0;
    border-radius: 0;
  }
  
  :deep(.el-dialog__header) {
    background: #f5f5f5;
    padding: 15px 20px;
    border-bottom: 1px solid #e4e7ed;
  }
  
  :deep(.el-dialog__body) {
    padding: 0;
    height: calc(100vh - 60px);
    overflow-y: auto;
  }
}

.flow-content {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100%;
}

.product-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.product-info h2 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 24px;
}

.product-details {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.detail-item {
  color: #606266;
  font-size: 14px;
}

.statistics-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card.blue .stat-number {
  color: #409eff;
  font-size: 28px;
  font-weight: bold;
}

.stat-card.orange .stat-number {
  color: #e6a23c;
  font-size: 28px;
  font-weight: bold;
}

.stat-label {
  color: #666;
  font-size: 14px;
  margin-top: 8px;
}

.action-buttons {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

/* 关闭按钮样式 */
.close-button-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 2001;
}

.close-button {
  width: 60px;
  height: 60px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
}

.close-button:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

.close-button .el-icon {
  font-size: 24px;
}
</style>
